//
//  FoodsHomeViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/26.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "FoodsHomeViewController.h"
#import "FoodsStoreViewController.h"
#import "FoodsHomeTableViewCell.h"
#import "QuestionTypeTableViewCell.h"
#import "FoodsHomeCollectionViewCell.h"
#import "SingleChoseMenu.h"
#import "EntertainmentTableViewCell.h"

static NSString * cellIndentfier = @"EntertainmentTableViewCell";
static NSString * typeCellIndentfier = @"QuestionTypeTableViewCell";

@interface FoodsHomeViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,DYQBannerScrollViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property(nonatomic,assign)CGFloat offSet;

@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray * storeTypesArray;
@property(nonatomic,strong)NSString * storeTypeId;
/*****/
@property (strong,nonatomic) DYQBannerScrollView *bannerScrollView;//广告栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIView *navSearchBackView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UIView *typeView;
@property (strong, nonatomic) IBOutlet UIButton *maskView;
@property (strong, nonatomic) IBOutlet UITextField *searchField;
@property (strong, nonatomic) IBOutlet UITableView *typeTableView;//筛选tableView
@property (strong, nonatomic) IBOutlet UITableView *listTableView;//商品展示tableView
@property (strong, nonatomic) IBOutlet UIView *pickView;
@property (strong, nonatomic) IBOutlet UIButton *typeButton;//分类
@property (strong, nonatomic) IBOutlet UIButton *typeSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *pickSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *pickButton;//筛选
@property (strong, nonatomic) IBOutlet UIButton *rankButton;//智能排序
@property (strong, nonatomic) IBOutlet UIButton *rankSmallButton;
@property (strong, nonatomic) IBOutlet UIButton *imageButton;//搜索图片
@property(nonatomic,strong)UIButton * currentButton;
@property(strong,nonatomic)NSMutableArray * typesArray;
@property(strong,nonatomic)NSMutableArray * rankArray;
@property(strong,nonatomic)NSMutableArray * pickArray;
@property(strong,nonatomic)NSMutableDictionary * choseTypeDic;
@property(nonatomic,strong)NSMutableArray * foodsArray;


@property(nonatomic,assign)NSInteger forSaleIndex;
@property(nonatomic,assign)NSInteger priceIndex;
@end

@implementation FoodsHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _forSaleIndex = -1;
    _priceIndex = -1;
    _choseTypeDic = [NSMutableDictionary dictionary];
    _typesArray = [NSMutableArray array];
    _foodsArray = [NSMutableArray array];
    _imageArray = [NSMutableArray array];
    _rankArray = [NSMutableArray array];
    _pickArray = [NSMutableArray array];
    _storeTypesArray = [NSMutableArray array];
    [self initViewLayout];
    [self getStoresTypes];
    [self getAdvertiseBanner];
    [self addRefreshing];

    
}


- (void)initViewLayout{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.typeView];
    [self adaptiveViewLayout:self.pickView];
    _navSearchBackView.layer.borderWidth = 1;
    _navSearchBackView.layer.borderColor = [UIColor colorWithWhite:0.882 alpha:1.000].CGColor;
    _navSearchBackView.layer.cornerRadius = 15*VerticalRatio();
    
    
    //广告栏
    self.bannerScrollView = [[DYQBannerScrollView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 115), NO)];
    self.bannerScrollView.backgroundColor = [UIColor clearColor];
    self.bannerScrollView.pageControlPosition = PageControlPositionCenter;
    self.bannerScrollView.noDataPlaceholderImage = [UIImage imageNamed:@"cover_cy"];
    self.bannerScrollView.timeInterval = 3;
    self.bannerScrollView.pageControllerTintColor = [UIColor whiteColor];
    self.bannerScrollView.pageControllerCurrentColor = [UIColor orangeColor];
    
    [self.scroView addSubview:_bannerScrollView];
    
    self.scroView.frame = flexibleFrame(CGRectMake(0, 64, 320, 504), NO);
    self.scroView.contentSize = flexibleSize(CGSizeMake(0, 653), YES);
    
    
    [self.listTableView registerNib:[UINib nibWithNibName:cellIndentfier bundle:nil] forCellReuseIdentifier:cellIndentfier];
    _listTableView.dataSource = self;
    _listTableView.delegate = self;

    [self.typeTableView registerNib:[UINib nibWithNibName:typeCellIndentfier bundle:nil] forCellReuseIdentifier:typeCellIndentfier];
    
    SingleChoseMenu * forSaleMenu = [[SingleChoseMenu alloc]initWithFrame:flexibleFrame(CGRectMake(0, 35, 320, 30), NO) titles:@[@"团购",@"代金券"] XInterval:10 YInterval:10 defaultColor:[UIColor colorWithRed:0.008 green:0.102 blue:0.141 alpha:1.000] colors:nil cancleSelect:(BOOL)YES complect:^(NSInteger index) {
        _forSaleIndex = index;
        [self pickHandel];
        
    }];
    [_pickView addSubview:forSaleMenu];
    
    SingleChoseMenu * priceMenu = [[SingleChoseMenu alloc]initWithFrame:flexibleFrame(CGRectMake(0, 110, 320, 70), NO) titles:@[@"30以下",@"30-50",@"51-100",@"100以上"] XInterval:10 YInterval:10 defaultColor:[UIColor colorWithRed:0.008 green:0.102 blue:0.141 alpha:1.000] colors:nil cancleSelect:(BOOL)YES complect:^(NSInteger index) {
        _priceIndex = index;
         [self pickHandel];
    }];
    [_pickView addSubview:priceMenu];
    
    self.searchField.delegate = self;
    
    
    UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.collectionViewLayout = flowLayout;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    self.scroView.delegate = self;
}

#pragma mark ===== 店铺分类
- (void)getStoresTypes{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"20169616" forKey:@"mstyId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryShopTypes withHttpType:@"POST" withTag:SX_SX_queryShopTypes];
}

#pragma mark  ==== scroViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _listTableView || scrollView== _scroView) {
        _offSet = scrollView.contentOffset.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _listTableView || scrollView == _scroView ) {
        if (scrollView.contentOffset.y>_offSet) {
            
            [_scroView setContentOffset:CGPointMake(0, 187*VerticalRatio()) animated:YES];
            _scroView.scrollEnabled = NO;
            _listTableView.scrollEnabled = YES;
        }else{
            if (scrollView == _scroView) {
                [_scroView setContentOffset:CGPointMake(0, 0) animated:YES];
                _scroView.scrollEnabled = YES;
                _listTableView.scrollEnabled = NO;
            }else{
                if (decelerate == YES) {
                    [_scroView setContentOffset:CGPointMake(0, 0) animated:YES];
                    _scroView.scrollEnabled = YES;
                    _listTableView.scrollEnabled = NO;
                }
            }
            
        }
    }
}

#pragma mark - 返回
- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark === 筛选类型
- (IBAction)choseType:(UIButton *)sender {
    
    UIButton * smallbutton = [[UIButton alloc]init];
    if (sender==_rankButton) {
        smallbutton = _rankSmallButton;
    }else{
        smallbutton = _pickSmallButton;
    }
    
    if (smallbutton == _currentButton) {
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        [UIView animateWithDuration:0.5 animations:^{
            _typeTableView.frame = flexibleFrame(CGRectMake(0, 225, 320, 0), NO);
            _maskView.alpha = 0;
        }completion:^(BOOL finished) {
            _maskView.hidden = YES;
        }];
        _currentButton = nil;
        return;
    }

    _typeTableView.dataSource = self;
    _typeTableView.delegate = self;
    
    UIButton * button = [[UIButton alloc]init];
    if (sender == _typeButton) {
        button = _typeSmallButton;
    }else if(sender == _pickButton){
        button = _pickSmallButton;
    }else{
        button = _rankSmallButton;
    }
    
    if (button != _currentButton) {
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        _currentButton = button;
    }
    
    NSInteger lines = 0;
    if (sender == _typeButton) {
//        _typeButton.selected = YES;
//        _typeSmallButton.selected = YES;
//        _rankButton.selected = NO;
//        _rankSmallButton.selected = NO;
//        _pickButton.selected = NO;
//        _pickSmallButton.selected = NO;
//        [_typeSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
//        lines = _typesArray.count;
        
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _rankButton.selected = YES;
        _rankSmallButton.selected = YES;
        _pickButton.selected = NO;
        _pickSmallButton.selected = NO;
        [_rankSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
        
        _pickView.hidden = YES;
        _typeTableView.hidden = NO;
        _rankArray =[@[@"智能排序",@"评价最高",@"人气最高",@"人均最低",@"人均最高"]mutableCopy];
        lines = _rankArray.count;
        
    }else if (sender == _rankButton){
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _rankButton.selected = YES;
        _rankSmallButton.selected = YES;
        _pickButton.selected = NO;
        _pickSmallButton.selected = NO;
        [_rankSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
        
        _pickView.hidden = YES;
        _typeTableView.hidden = NO;
        _rankArray =[@[@"全部分类",@"火锅",@"全部中餐",@"自助餐",@"甜点饮品",@"其他美食",@"KTV"]mutableCopy];
        lines = _rankArray.count;
    }else{
        _typeButton.selected = NO;
        _typeSmallButton.selected = NO;
        _rankButton.selected = NO;
        _rankSmallButton.selected = NO;
        _pickButton.selected = YES;
        _pickSmallButton.selected = YES;
        [_pickSmallButton.layer addAnimation:[self rotation:0.3 degree:M_PI direction:1 repeatCount:0] forKey:nil];
//
//        _typeTableView.hidden = YES;
//        _pickView.hidden = NO;
//        _forSaleIndex = -1;
//        _priceIndex = -1;

        _pickView.hidden = YES;
        _typeTableView.hidden = NO;
        _pickArray = [@[@"智能排序",@"评价最高",@"销量最高"]mutableCopy];
        lines = _pickArray.count;
    }
    
    
    if (lines>5) {
        lines = 5;
    }

    [UIView animateWithDuration:0.5 animations:^{
        _typeTableView.frame = flexibleFrame(CGRectMake(0, 225, 320, 45*lines), NO);
        _maskView.alpha = 1;
    }completion:^(BOOL finished) {
        _maskView.hidden = NO;
    }];
     [_typeTableView reloadData];
  
}

#pragma mark == 筛选
- (void)pickHandel{
    if (_forSaleIndex!=-1 && _priceIndex!=-1) {
        _pickView.hidden = YES;
        _maskView.alpha = 0;
        _maskView.hidden = YES;
        [self addRefreshing];
    }

}

- (IBAction)closeTypeView:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _typeTableView.frame = flexibleFrame(CGRectMake(0, 225, 320, 0), NO);
        _pickView.hidden = YES;
        _maskView.alpha = 0;
    }completion:^(BOOL finished) {
        _maskView.hidden = YES;
    }];
    [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
}


#pragma mark  获取首页广告BANNER--=========================================
-(void)getAdvertiseBanner{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryMallADDData" forKey:@"method"];
    [dic setObject:@"1" forKey:@"position"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_ADBanner withHttpType:@"POST" withTag:SX_kADBannerTag];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getFoodsList];
        });
    }];
    // 马上进入刷新状态
    [self.scroView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.foodsArray.count == _totle) {
        [self.listTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getFoodsList];
        });
    }
    
}



#pragma mark  获取美食列表--=====
- (void)getFoodsList{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:1]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    if (!_storeTypeId) {
        [dic setObject:@"20156572" forKey:@"storeTypeId"];
    }else{
        [dic setObject:_storeTypeId forKey:@"storeTypeId"];
    }
    if (_searchField.text.length>0) {
        [dic setObject:_searchField.text forKey:@"storeName"];
    }
    
    NSIndexPath * path = _choseTypeDic[@"rank"];
    if (path) {
        if (path.row==0) {
           [dic setObject:@"" forKey:@"mgstId"];
        }else{
        [dic setObject:[NSString stringWithFormat:@"%ld",path.row] forKey:@"mgstId"];
        }
        
    }else{
        [dic setObject:@"" forKey:@"mgstId"];
    }
    
    NSIndexPath * pickpath = _choseTypeDic[@"pick"];
    if (pickpath) {
        if (pickpath.row==0) {
            [dic setObject:@"-1" forKey:@"typeId"];
        }else{
            [dic setObject:[NSString stringWithFormat:@"%ld",pickpath.row] forKey:@"typeId"];
        }
        
    }else{
        [dic setObject:@"-1" forKey:@"typeId"];
    }
   
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryLineShop withHttpType:@"POST" withTag:SX_SX_queryLineShop];
    
}

#pragma mark ====旋转动画======
-(CABasicAnimation *)rotation:(float)dur degree:(float)degree direction:(int)direction repeatCount:(int)repeatCount
{
    CATransform3D rotationTransform = CATransform3DMakeRotation(degree, 0, 0, direction);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.toValue = [NSValue valueWithCATransform3D:rotationTransform];
    animation.duration  =  dur;
    animation.autoreverses = NO;
    animation.cumulative = NO;
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.repeatCount = repeatCount;
    animation.delegate = self;
    
    return animation;
    
}


#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _storeTypesArray.count;
}
//定义展示的Section的个数
-(NSInteger)nmumberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(80*VerticalRatio(), 67*VerticalRatio());
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0,0, 0, 0);
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    FoodsHomeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FoodsHome" forIndexPath:indexPath];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:[Common stringFromData:_storeTypesArray[indexPath.row][@"mstyImageUrl"]]]];
    cell.titleLabel.text = [Common stringFromData:_storeTypesArray[indexPath.row][@"mstyName"]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    _storeTypeId = [Common stringFromData:_storeTypesArray[indexPath.row][@"mstyId"]];
    [self.scroView.header beginRefreshing];
}
#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

        return 1;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _listTableView) {
        return 146*VerticalRatio();
        
    }else{
        return 45*VerticalRatio();
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _typeTableView) {
        if (_typeButton.selected) {
            return _typesArray.count;
        }else if (_rankButton.selected){
            return _rankArray.count;
        }else if(_pickButton.selected){
            return _pickArray.count;
        }
    }else{
        return _foodsArray.count;
    }
    return 0;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView != _listTableView) {
        QuestionTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:typeCellIndentfier];
        if (cell == nil) {
            cell= [[QuestionTypeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:typeCellIndentfier];
            
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        cell.typeName.textColor = [UIColor colorWithWhite:0.243 alpha:1.000];
        cell.typeButton.selected = NO;
        NSIndexPath * path = [[NSIndexPath alloc]init];
        if (_rankButton.selected==YES) {
            cell.typeName.text = [NSString stringWithFormat:@"%@",_rankArray[indexPath.row]];
            path = _choseTypeDic[@"rank"];
        }else if (_typeButton.selected==YES) {
            cell.typeName.text = [NSString stringWithFormat:@"%@",_typesArray[indexPath.row][@"mgcaName"]];
            path = _choseTypeDic[@"type"];
        }else if (_pickButton.selected==YES){
//            cell.typeName.text = [NSString stringWithFormat:@"%@",_pickArray[indexPath.row]];
//            path = _choseTypeDic[@"pick"];
            cell.typeName.text = [NSString stringWithFormat:@"%@",_pickArray[indexPath.row]];
            path = _choseTypeDic[@"pick"];
        }
        
        if (indexPath == path) {
            cell.typeName.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.086 alpha:1.000];
            cell.typeButton.selected = YES;
        }
        return cell;
    }else{
        EntertainmentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentfier];
        if (cell == nil) {
            cell= [[EntertainmentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentfier];
            
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        cell.address.hidden = YES;
        cell.mapImage.hidden = YES;
        
        NSDictionary * dic = _foodsArray[indexPath.row];
        

        
        double star = [[NSString stringWithFormat:@"%f",[[Common stringFromData:dic[@"storeComm"]]floatValue ]/2] doubleValue];
        
        CommitStarsView * stars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(65, 115, 60, 12), NO) Stars:star];
        [cell addSubview:stars];
        
        
        cell.commentScore.text = [NSString stringWithFormat:@"%.1f分",[[Common stringFromData:dic[@"storeComm"]]floatValue ]/2];
        cell.titleLabel.text = [Common stringFromData:dic[@"mstoName"]];
        
        if ([Common stringFromData:dic[@"msgoBigImageId"]].length>0) {
            [cell.backImage sd_setImageWithURL:[NSURL URLWithString:[Common stringFromData:dic[@"msgoBigImageId"]]]];
        }
        
        if ([Common stringFromData:dic[@"storeImg"]].length>0) {
            [cell.brandImage sd_setImageWithURL:[NSURL URLWithString:[Common stringFromData:dic[@"storeImg"]]]];
        }
        
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _listTableView) {
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
        FoodsStoreViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"FoodsStore"];
        page.foodId = _foodsArray[indexPath.row][@"mstoId"];
        [self.navigationController   pushViewController:page animated:YES];
        
    }else{
        
        NSString * key = @"";
        
       
        if (_currentButton == _typeSmallButton) {
            [_typeButton setTitle:_typesArray[indexPath.row] forState:UIControlStateNormal];
            CGSize size = [_typeButton.titleLabel.text sizeWithFont:_typeButton.titleLabel.font];
            if (size.width>_typeButton.frame.size.width) {
                size.width = _typeButton.frame.size.width-_typeSmallButton.frame.size.width;
            }
            _typeSmallButton.frame =CGRectMake(CGRectGetMinX(_typeButton.frame)+(_typeButton.frame.size.width-size.width)/2+size.width+1, _typeSmallButton.frame.origin.y, _typeSmallButton.frame.size.width, _typeSmallButton.frame.size.height);
            key = @"type";
        }else if (_currentButton == _rankSmallButton){
            [_rankButton setTitle:_rankArray[indexPath.row] forState:UIControlStateNormal];
            CGSize size = [_rankButton.titleLabel.text sizeWithFont:_rankButton.titleLabel.font];
            if (size.width>_rankButton.frame.size.width) {
                size.width = _rankButton.frame.size.width-_rankSmallButton.frame.size.width;
            }
            _rankSmallButton.frame =CGRectMake(CGRectGetMinX(_rankButton.frame)+(_rankButton.frame.size.width-size.width)/2+size.width+1, _rankSmallButton.frame.origin.y, _rankSmallButton.frame.size.width, _rankSmallButton.frame.size.height);
            key = @"rank";
        }else{
            [_pickButton setTitle:_pickArray[indexPath.row] forState:UIControlStateNormal];
            CGSize size = [_pickButton.titleLabel.text sizeWithFont:_pickButton.titleLabel.font];
            if (size.width>_pickButton.frame.size.width) {
                size.width = _pickButton.frame.size.width-_pickSmallButton.frame.size.width;
            }
            _pickSmallButton.frame =CGRectMake(CGRectGetMinX(_pickButton.frame)+(_pickButton.frame.size.width-size.width)/2+size.width+1, _pickSmallButton.frame.origin.y, _pickSmallButton.frame.size.width, _pickSmallButton.frame.size.height);
            key = @"pick";
        }
        
        NSIndexPath * path = _choseTypeDic[key];
        QuestionTypeTableViewCell * cell = [_typeTableView cellForRowAtIndexPath:path];
        cell.typeButton.selected = NO;
        cell.typeName.textColor = [UIColor colorWithWhite:0.243 alpha:1.000];
        
        QuestionTypeTableViewCell * Cell = [_typeTableView cellForRowAtIndexPath:indexPath];
        Cell.typeButton.selected = YES;
        Cell.typeName.textColor = [UIColor colorWithRed:1.000 green:0.643 blue:0.086 alpha:1.000];
        
        [_choseTypeDic setObject:indexPath forKey:key];

        
        [UIView animateWithDuration:0.5 animations:^{ _typeTableView.frame = flexibleFrame(CGRectMake(0, 225, 320, 0), YES);
            _maskView.alpha = 0;
        }completion:^(BOOL finished) {
            _maskView.hidden = YES;
        }];
        [_currentButton.layer addAnimation:[self rotation:0.3 degree:2*M_PI direction:1 repeatCount:0] forKey:nil];
        _currentButton = nil;

        [self.scroView.header beginRefreshing];
    }
    
}

#pragma   mark---- textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [self.scroView.header beginRefreshing];
    return YES;
}

#pragma mark----DYQBannerScrollViewDelegate

-(void)bannerScrollView:(DYQBannerScrollView *)bannerScrollView didSelectItemAtIndex:(NSInteger)index
{
    //    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"PersonCenterStoryboard" bundle:nil];
    //    WebDetailInfoViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"WebDetailInfo"];
    //    page.objectId = _bannerArray[index][@"appAdertUrl"];
    //    page.titleStr = @"详情";
    //    page.meType = @"4";
    //    [self.navigationController  pushViewController:page animated:YES];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroView.header endRefreshing];
    [_listTableView.footer endRefreshing];
    
    if (tag==SX_kADBannerTag) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [self.imageArray removeAllObjects];
            //            self.imageArray = database[@"result"];
            for (NSDictionary *data in database[@"result"]) {
                NSString * picture = [Common stringFromData:data[@"appAdertImagUri"]];
                [self.imageArray addObject:picture];
            }
            _bannerScrollView.imageUrls = _imageArray;
            _bannerScrollView.delegate = self;

           
            
        }
    }else if (tag == SX_SX_queryLineShop){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
        [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        
    }else  {
        dispatch_async(dispatch_get_main_queue(), ^{
            _totle = [database[@"result"][@"totalResults"] integerValue];
            if (_totle > PageSize) {
                __weak __typeof(self) weakSelf = self;
                if (!self.listTableView.footer) {
                    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                    self.listTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                        [weakSelf loadMoreData];
                    }];
                }
            }
            if (self.pageNO == 1) {
                [self.foodsArray removeAllObjects];
            }
            NSArray *arr = database[@"result"][@"pageRecord"];
//            NSArray *arr = database[@"result"];
            for (id entity in arr) {
                [self.foodsArray addObject:entity];
            }
            _listTableView.dataSource = self;
            _listTableView.delegate = self;
            [_listTableView reloadData];
            
        });

    }
    }else if (tag==SX_SX_queryShopTypes){
    
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _storeTypesArray = database[@"result"];
            
            [_collectionView reloadData];
        }
    }
    
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}



@end
